package fudan.secret.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.*;

import org.apache.struts2.json.annotations.JSON;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import fudan.secret.domain.Image;
import fudan.secret.domain.User;
import fudan.secret.util.HibernateSessionFactory;

public class FindPersonAction extends ActionSupport{
	  private int uid;
	  private String uname;
	  private String unickname;
	  private Map<String,String> map;
	 
	  @JSON(serialize=false)
	  public int getUid(){
		  return uid;
	  }
	  
	  public void setUid(int id){
		  uid = id;
	  }
	  
	  @JSON(serialize=false)
	  public String getUname(){
		  return uname;
	  }
	  
	  public void setUname(String name){
		  uname = name;
	  }
	  
	  
	  @JSON(serialize=false)
	  public String getUnickname(){
		  return unickname;
	  }
	  
	  public void setUnickname(String nickname){
		  unickname = nickname;
	  }
	  
	  public Map<String, String> getResult() {  
	      return map;  
	   }  
	  
	  
	  public String execute() throws Exception{
		  Session session = HibernateSessionFactory.getSession();
		  Transaction tx = null;
		  map = new HashMap<String,String>();
		  try{
			  Criteria crit = session.createCriteria(User.class);
			  if(uid!=0){
			    crit.add(Restrictions.eq("uid", uid));
			  }else if(uname!=null && uname.length()!=0){
				crit.add(Restrictions.eq("uname", uname));
			  }else if(unickname!=null && unickname.length()!=0){
				crit.add(Restrictions.eq("unickname", unickname)); 
			  }else{
				  session.close();
				  return SUCCESS;
			  }
			  User users = (User) crit.uniqueResult();
			  if(users != null){
					map.put("uid", String.valueOf(users.getUid()));
					map.put("uname", users.getUname());
					map.put("unickname", users.getUnickname());
					if(users.getUpolicy()!=1){
					  map.put("ugender", users.getUgender());
					  map.put("uschool",String.valueOf(users.getUschool()));
					  map.put("umobile", users.getUmobile());
					  map.put("uemail", users.getUemail());
					  map.put("findperson", "true");
					}else{
						map.put("findperson", "private");
					}
					if(users.getUimgid()!=1){
						int imgid = users.getUimgid();
						Criteria crit_img = session.createCriteria(Image.class);
						Image img = (Image) crit_img.uniqueResult();
						map.put("portrait", img.getImgcontent().toString());
					}else{
						map.put("uicon", "null");
					}
			  } else {
				  map.put("findperson", "false");
			  }
		  } catch(Exception e) {
			  map.put("findperson", "error");
			  e.printStackTrace();
			  tx.rollback();
		  } finally {
			  session.close();
		  }
		  return SUCCESS;
	  }
}
